import { Space, message, Button, Tag, Transfer } from 'antd';
import ProForm, {
    ModalForm
} from '@ant-design/pro-form';
import React, { useEffect, useRef, useState } from 'react';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ModalProps } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import { CloseOutlined } from '@ant-design/icons';
import { useIntl } from 'umi';
import { getApiUserAll as GetUsers } from '@/services/furion-cms/user';
import { putApiRoleByIdUsers as UpdateUsers } from '@/services/furion-cms/role';

interface RoleAuthorizeProps {
    modalVisible?: boolean;
    recored?: Partial<API.RoleDto & { users: number[] }>;
    onVisibleChange: (visit: boolean) => void;
    modalProps?: Omit<ModalProps, 'visible'>;
}

const RoleAuthorize: React.FC<RoleAuthorizeProps> = (props) => {
    const { modalVisible, onVisibleChange, modalProps, recored } = props;
    /**
         * @en-US International configuration
         * @zh-CN 国际化配置
         * */
    const intl = useIntl();
    const [distributionData, setDistributionData] = useState<APP.DistributionData[]>();

    // 绑定一个 ProFormInstance 实例
    const formRef = useRef<ProFormInstance>();

    useEffect(() => {
        (async () => {
            try {
                const { data } = await GetUsers();
                setDistributionData(data?.map((m: any) => ({
                    key: m.id,
                    title: m.nickName,
                    description: m.nickName
                })));
            } catch { }
        })();
    }, [modalVisible, recored]);// eslint-disable-line react-hooks/exhaustive-deps

    const finishHandle = (values: { users: number[] }) => {
        console.log('finishHandle-data', values);
        return UpdateUsers({ id: recored!.id! }, values.users)
            .then(() => {
                message.success('角色授权成功')
                return true;
            })
    }

    return (
        <ModalForm
            modalProps={{
                destroyOnClose: true,
                width: 580,
                maskClosable: false,
                ...modalProps
            }}
            visible={modalVisible}
            formRef={formRef}
            initialValues={recored}
            onFinish={finishHandle}
            onVisibleChange={onVisibleChange}
        >
            <ProDescriptions<API.RoleDto> column={2}
                dataSource={recored}
                title="角色授权"
                tooltip="授权当前角色给指定的用户"
                extra={<Button type="text" icon={<CloseOutlined />} onClick={() => onVisibleChange(false)} />}
                columns={[
                    {
                        title: intl.formatMessage({
                            id: 'pages.role.name',
                            defaultMessage: '名称'
                        }),
                        dataIndex: 'name',
                        render: (_, entity) => {
                            return <Space>
                                <span>{entity.name}</span>
                                {entity.hasSeed && <Tag color="magenta">内置</Tag>}
                                {entity.isDefault && <Tag color="blue">默认</Tag>}
                            </Space>;
                        }
                    },
                    {
                        title: intl.formatMessage({
                            id: 'pages.role.createdTime',
                            defaultMessage: '创建时间'
                        }),
                        dataIndex: 'createdTime',
                        valueType: "dateTime"
                    },
                    {
                        title: intl.formatMessage({
                            id: 'pages.role.description',
                            defaultMessage: '描述'
                        }),
                        dataIndex: 'description',
                        span: 2
                    }
                ]}
            />
            <ProForm.Item name="users" valuePropName="targetKeys" noStyle>
                <Transfer
                    titles={[
                        intl.formatMessage({
                            id: 'component.transfer.source',
                            defaultMessage: '未分配'
                        }),
                        intl.formatMessage({
                            id: 'component.transfer.target',
                            defaultMessage: '已分配'
                        })
                    ]}
                    dataSource={distributionData}
                    onChange={(newTargetKeys, direction, moveKeys) => {
                        console.log(newTargetKeys, direction, moveKeys);
                        formRef.current?.setFieldsValue({
                            users: newTargetKeys
                        })
                    }}
                    listStyle={{
                        height: 300,
                    }}
                    render={item => item.title}
                    pagination
                    showSearch
                />
            </ProForm.Item>
        </ModalForm>
    );
}

export default RoleAuthorize;